package com.javen.zookeeper.order;

import com.javen.zookeeper.lock.DistributedLock;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Javen
 */
@Slf4j
public class OrderService implements Runnable {
    private final OrderGenerator orderGenerator = new OrderGenerator();
    private final java.util.concurrent.locks.Lock lock = new ReentrantLock();
    AtomicLong atomicLong = new AtomicLong();

    @Override
    public void run() {
//        unLockGen();
//        sysLockGen();
//        getNumber();
//        zkLockGen();

        distributedLockGen();
    }

    public void unLockGen() {
        log.info(Thread.currentThread().getName() + ":orderId:" + orderGenerator.getNumber());
    }

    public synchronized void sysLockGen() {
        log.info(Thread.currentThread().getName() + ":orderId:" + orderGenerator.getNumber());
    }

    public void getNumber() {
        lock.lock();
        try {
            log.info(Thread.currentThread().getName() + ":orderId:" + orderGenerator.getNumber());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void distributedLockGen() {
        DistributedLock lock = new DistributedLock("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183", "node" + atomicLong.getAndIncrement());
        lock.lock();
        try {
            log.info(Thread.currentThread().getName() + ":orderId:" + orderGenerator.getNumber());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        int count = 50;
        OrderService orderService = new OrderService();

        ThreadFactory namedThreadFactory = Thread::new;
        ExecutorService executor = new ThreadPoolExecutor(5, Integer.MAX_VALUE,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i < count; i++) {
            executor.submit(orderService);
        }
        executor.shutdown();
    }

}



